<?php
use Base\AdminController;
use Illuminate\Support\Str;
use JetBrains\PhpStorm\NoReturn;
use Traits\DataTree;

class RoleController extends AdminController
{
    use DataTree;

    protected string $table = "roles";

    protected string $model = "role";

    #[NoReturn] public function init(): void
    {
        if (Request::input("title")) {
            $this->where[] = ['title','like', '%'.Request::input("title").'%'];
        }
        $this->routeWhiteLst = ['role@usercheck','role@user'];
        parent::init();
		if ($this->member_id!=1) {
            $this->where[] = ['id','<>',1];
        }
    }

    /**
     * 获取所有角色
     * @return void
     */
    #[NoReturn] public function getAllAction(): void
    {
        $user = UserModel::query()->with(["role"])->where("id",$this->member_id)->first();
        $role_id = [];
        if ($this->member_id!=1) {
            $role_id = $user->role->pluck("role_id")->toArray();
            $roleId = RoleModel::query()->whereIn("pid", $role_id)->get()->pluck("id")->toArray();
            $role_id = array_merge($role_id, $roleId);
        }
        $data = RoleModel::query()
            ->when($role_id,function ($query,$value) {
                $query->whereIn("id", $value);
            })
            ->selectRaw("id,title as label,pid")
            ->get()
            ->toArray();
        $data = $this->getTree($data);
        $this->apiSuccess($data,"获取成功",20000);
    }

    /**
     * 显示
     * @return void
     */
    #[NoReturn] protected function operate(): void
    {
        $info = RoleModel::query()->with(["permissions"])->where('id', Request::input("ids"))->first();
        if (!$info) $this->apiError("数据不存在");
        $info['menu_ids'] = $info->permissions->pluck("permission_id");
        unset($info['permissions']);
        $org_id = RoleHasOrganizationModel::query()->where("role_id",$info['id'])->get()->pluck("org_id");
        $info['org_id'] = $org_id->toArray();
        $this->apiSuccess($info->toArray(),"获取成功",20000);

    }

    /**
     * 修改
     * @return void
     */
    protected function update(): void
    {
        DB::beginTransaction();
        try {
            $params  = Request::all();
            unset($params['org_id']);
            $this->cleanCache();
            $params['menu_ids'] = implode(",",$params['menu_ids']);
            $insert = [];
            if (Request::input("id") !== null) {
                $role = RoleModel::query()->where("id",Request::input("id"))->first();
                if (!$role) $this->apiError("数据不存在");
                RoleModel::query()->where("id",Request::input("id"))->update($params);
                RoleHasPermissionModel::where("role_id",$role['id'])->delete();
                foreach (Request::input("menu_ids") as $vo) {
                    $insert[] = [
                        "role_id"=>$role->id,
                        "permission_id"=>$vo,
                    ];
                }
                RoleHasPermissionModel::insert($insert);
                if (is_numeric(Request::input("data_range"))) {
                    $this->roleAuthData($role->id);
                }
                DB::commit();
                $this->apiSuccess([],"更新成功",20000);
            }else {
                $params['uuid'] = (string)Str::uuid();
                $params['created_at'] = date("Y-m-d H:i:s");
                $res =  RoleModel::insertGetId($params);
                $info =  RoleModel::query()->where('id',$res)->first();
                foreach (Request::input("menu_ids") as $vo) {
                    $insert[] = [
                        "role_id"=>$info->id,
                        "permission_id"=>$vo,
                    ];
                }
                RoleHasPermissionModel::insert($insert);
                if (is_numeric(Request::input("data_range"))) {
                    $this->roleAuthData($res);
                }
                DB::commit();
                $this->apiSuccess( $info->toArray(),"新增成功",20000);
            }
        } catch (Exception $exception) {
            DB::rollBack();
            Log::$customFileName = LOG_PATH."/errors/";
            Log::error($exception->getMessage().$exception->getTraceAsString());
            $this->apiError($exception->getMessage());
        }
    }

    /**
     * 角色数据授权
     * @param $role_id
     * @return void
     */
    protected function roleAuthData($role_id): void
    {
        // 全部数据:1;仅自己:0;所属组织:2;所属组织及以下:3;自定义:4
        $role_org = [];
        switch (Request::input("data_range")) {
            case 4:
                foreach (Request::input("org_id") as $vo) {
                    $role_org[] = [
                        'role_id'=>$role_id,
                        'org_id'=>$vo,
                    ];
                }
                break;
            case 1:
                $role_org[] = [
                    'role_id'=>$role_id,
                    'org_id'=>1,
                ];
                break;
        }
        RoleHasOrganizationModel::where("role_id",$role_id)->delete();
        RoleHasOrganizationModel::insert($role_org);
    }

    /**
     * 获取组织下的用户
     * @return void
     */
    #[NoReturn] public function userAction(): void
    {
        try {
            $org = OrganizationModel::query()->where("id",Request::input("id"))->first();
            $user_id = [];
            if (Request::input("role_id")) {
                $user_id = UserHasRoleModel::query()->where("role_id", Request::input("role_id"))
                    ->get()->pluck("user_id")->toArray();
            }
            $sql = OrganizationUserModel::query()
                ->join("users","users.id","=","organization_users.user_id")
                ->when($user_id,function ($query) use($user_id) {
                    $query->whereNotIn("organization_users.user_id",$user_id);
                })
                ->when(Request::input("title"),function ($query,$value) {
                    $query->where("users.nickname","like","%".$value."%");
                });
            if ($org['id']!=1) {
                $sql->org($org['id']);
            }
            $data = $sql->paginate(Request::input("limit",10),['*'],NULL,Request::input("p",1));
            $result = [
                'items' => collect($data->items())->toArray(),
                'total'=>$data->total(),
                'per_page' => $data->perPage(),
                'page' => $data->currentPage()
            ];
            $this->apiSuccess($result,"获取成功",20000);
        }catch (Exception $exception) {
            Log::$customFileName = LOG_PATH."/errors/";
            Log::error($exception->getMessage().$exception->getTraceAsString());
            $this->apiError($exception->getMessage());
        }
    }

    /**
     * 获取已授权用户
     * @return void
     */
    #[NoReturn] public function userCheckAction(): void
    {
        try {
            $sql = OrganizationUserModel::query()
                ->join("users","users.id","=","organization_users.user_id")
                ->whereHas("roleExits",function ($query) {
                    $query->where("role_id",Request::input('role_id'));
                });
            if (Request::input("id")!=1) {
                $sql->org(Request::input("id"));
            }
            $data = $sql->get();
            $this->apiSuccess($data->toArray(),"获取成功",20000);
        }catch (Exception $exception) {
            Log::$customFileName = LOG_PATH."/errors/";
            Log::error($exception->getMessage().$exception->getTraceAsString());
            $this->apiError($exception->getMessage());
        }
    }


    /**
     * 角色授权用户
     * @return void
     */
    #[NoReturn] public function userAuthAction(): void
    {
        DB::beginTransaction();
        try {
            if (!Request::input("user_ids")) {
                UserHasRoleModel::where("role_id", Request::input("role_id"))->delete();
            }else{
                UserHasRoleModel::where("role_id", Request::input("role_id"))->whereIn("user_id", Request::input("user_ids"))->delete();
                $insert = [];
                foreach (Request::input("user_ids") as $vo) {
                    $insert[] = [
                        "role_id" => Request::input("role_id"),
                        "user_id" => $vo,
                    ];
                }
                UserHasRoleModel::insert($insert);
            }
            DB::commit();
            $this->apiSuccess([],"操作成功",20000);
        }catch (Exception $exception) {
            DB::rollBack();
            Log::$customFileName = LOG_PATH."/errors/";
            Log::error($exception->getMessage().$exception->getTraceAsString());
            $this->apiError($exception->getMessage());
        }
    }
}
